/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-06-08 09:06:42
 * @Last Modified by: xushuhao
 * @Last Modified time: 2020-07-21 09:08:16
 * @Description: TabBar导航 框架
 */

import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_center_bubble_button.dart';
import 'package:flutter_code_framework/pages/class_room_page.dart';
import 'package:flutter_code_framework/pages/lessons_page.dart';
import 'package:flutter_code_framework/pages/my_page.dart';
import 'package:flutter_code_framework/pages/resources_page.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/widgets/my_progress_dialog.dart';
import 'package:flutter_code_framework/widgets/x_dialog_page.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info/package_info.dart';

class BaseMainTabbarPage extends StatefulWidget {
  BaseMainTabbarPage({Key key}) : super(key: key);

  _BaseMainTabbarPageState createState() => _BaseMainTabbarPageState();
}

class _BaseMainTabbarPageState extends State<BaseMainTabbarPage>
    with WidgetsBindingObserver, SingleTickerProviderStateMixin {
  Map args;
  Animation<double> animation;
  AnimationController controller;
  String _currentValue, fullSavePath;
  static ProgressDialog pr;

  var appBarTitles = ['备课', '班级', '', '资源', '我的'];

  var tabIcons = [
    Icons.explore,
    SFSymbols.person_2,
    SFSymbols.plus_circle_fill,
    Icons.videocam,
    SFSymbols.smiley,
  ];

  List<Widget> toobarClassNameList = [
    LessonsPage(),
    ClassroomPage(),
    null, //发布按钮 cupertino模式生效
    ResourcesPage(),
    MyPage(),
  ];

  int _tabIndex = G.tabIndex;
  bool _isOpenMenu = false; //是否打开泡泡菜单
  double bottomVsrtical = 0; //作为内部页面距离底部的高度

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Theme.of(context).backgroundColor,
      body: Stack(
        children: <Widget>[
          SafeArea(
            child: Container(
              width: getScreenWidth(),
              height: getMainWidgetHeight(),
              child: IndexedStack(
                index: _tabIndex,
                alignment: AlignmentDirectional.bottomCenter,
                children: <Widget>[
                  LessonsPage(),
                  ClassroomPage(),
                  Text(''), //占位发布按钮 cupertino模式生效
                  ResourcesPage(),
                  MyPage(),
                ],
              ),
            ),
          ),
          //中心按钮动画层
          _isOpenMenu
              ? GestureDetector(
                  child: BaseCenterBubbleButton(
                    animation: animation,
                    callBack: () {
                      controller.reverse().then((value) {
                        setState(() {
                          _isOpenMenu = false;
                        });
                      });
                    },
                  ),
                  onTap: () {
                    setState(() {
                      _isOpenMenu = false;
                    });
                  },
                )
              : Container(
                  width: 0,
                  height: 0,
                ),
        ],
      ),

      //两种风格选择 getTabBarMaterialView; getTabBarCupertinoView
      bottomNavigationBar: getTabBarMaterialView(),
      //getTabBarCupertinoView 时需要屏蔽以下两行代码
      floatingActionButtonLocation: getFloatingActionButtonLocation(),
      floatingActionButton: getFloatingActionButton(controller),
    );
  }

  FloatingActionButtonLocation getFloatingActionButtonLocation() {
    return FloatingActionButtonLocation.centerDocked;
  }

  Widget getFloatingActionButton(AnimationController controller) {
    return Container(
      width: 70,
      height: 70,
      padding: EdgeInsets.all(5),
      // TOP值越大 位置越向底部移动
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      decoration: BoxDecoration(
        //形状圆角值，越小越尖
        borderRadius: BorderRadius.circular(35),
        // color: G.buttonTextColor,
      ),
      child: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          // print("你点击了 中心 发布按钮 ");
          if (!_isOpenMenu) {
            setState(() {
              _isOpenMenu = true;
            });
            controller.forward();
          } else {
            controller.reverse().then((value) {
              setState(() {
                _isOpenMenu = false;
              });
            });
          }
        },
        //阴影
        elevation: 0,
        backgroundColor: Theme.of(context).accentColor,
      ),
    );
  }

//底部Tabbar布局 - Material风格
  Widget getTabBarMaterialView() {
    return BottomAppBar(
      shape: CircularNotchedRectangle(),
      notchMargin: 10.0,
      color: Theme.of(context).backgroundColor,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children:
            _getNewBottomAppBarItems(), //_getBottomAppBarItems(),_getNewBottomAppBarItems()
      ),
    );
  }

  ///返回屏幕高度
  double getScreenHeight() {
    return MediaQuery.of(context).size.height;
  }

  ///返回状态栏、顶部安全高度
  double getTopSafeHeight() {
    return MediaQuery.of(context).padding.top;
  }

  ///返回底部安全高度
  double getBottomSafeHeight() {
    return MediaQuery.of(context).padding.bottom;
  }

//返回自定义Tabbar 高度。
  double getTabBarHeight() {
    return kBottomNavigationBarHeight;
  }

  ///返回appbar高度，也就是导航栏高度
  double getAppBarHeight() {
    return kToolbarHeight;
  }

  ///返回屏幕宽度
  double getScreenWidth() {
    return MediaQuery.of(context).size.width;
  }

  double getMainWidgetHeight() {
    //此处在SafeArea内,所以减去top、bottom pad
    double screenHeight = getScreenHeight() -
        getTopSafeHeight() -
        getBottomSafeHeight() -
        bottomVsrtical;

    screenHeight = screenHeight - getTabBarHeight();

    return screenHeight;
  }

//material - 无文本
  List<IconButton> _getBottomAppBarItems() {
    double itemWidth = getScreenWidth() / 5.0;
    List<IconButton> list = List();
    var _padding = EdgeInsets.fromLTRB(30, 0, 30, 0);
    var _padding2 = EdgeInsets.fromLTRB(0, 0, 40, 0);
    var _padding3 = EdgeInsets.fromLTRB(40, 0, 0, 0);

    for (var i = 0; i < appBarTitles.length; i++) {
      if (i != 2) {
        list.add(IconButton(
                padding: (i == 1) ? _padding2 : (i == 3) ? _padding3 : _padding,
                icon: _getNavIcon(i),
                tooltip: _getNavTitle(i).toString(),
                onPressed: () {
                  setState(() {
                    _tabIndex = i;
                  });
                  G.tabIndex = i;
                  print('set state!!!!!!!! $_tabIndex');
                })

            // icon: _getNavIcon(i),
            // title: _getNavTitle(i),
            //activeIcon: Icon(Icons.payment, color: Colors.red),
            );
      }
    }
    return list;
  }

  //底部Tabbar布局 - cupertino风格
  Widget getTabBarCupertinoView() {
    return CupertinoTabBar(
      items: _getBottomNavItems(),
      backgroundColor: Theme.of(context).backgroundColor,
      currentIndex: _tabIndex,
      activeColor: Theme.of(context).backgroundColor,
      onTap: (index) {
        setState(() {
          _tabIndex = index;
        });
        G.tabIndex = index;
        RouteTransition(toobarClassNameList[_tabIndex])
            .pushReplacementTransRoute(context);
        print('set state!!!!!!!! $_tabIndex');
      },
    );
  }

  //cupertino
  List<BottomNavigationBarItem> _getBottomNavItems() {
    List<BottomNavigationBarItem> list = new List();
    for (var i = 0; i < appBarTitles.length; i++) {
      list.add(new BottomNavigationBarItem(
        icon: _getNavIcon(i),
        title: _getNavTitle(i),
        // activeIcon: Icon(Icons.payment, color: Colors.red),
      ));
    }
    return list;
  }

  // material 自定义tabbaritem 含文本
  List<Container> _getNewBottomAppBarItems() {
    List<Container> list = List();
    var _padding = EdgeInsets.fromLTRB(0, 8, 0, 8);
    for (var i = 0; i < appBarTitles.length; i++) {
      if (i != 2) {
        Icon _icon = _getNavIcon(i);
        //构造返回的Widget
        Container item = Container(
          padding: _padding,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              constraints: BoxConstraints(minWidth: getScreenWidth() / 5),
              // color: Colors.red,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  _icon,
                  _getNavTitle(i),
                ],
              ),
            ),
            onTap: () {
              if (_tabIndex != i) {
                setState(() {
                  _tabIndex = i;
                });
              }
              G.tabIndex = i;

              controller.reverse().then((value) {
                setState(() {
                  _isOpenMenu = false;
                });
              });

              // RouteTransition(toobarClassNameList[_tabIndex])
              //     .pushReplacementRoute(context);

              // print('当前_tabIndex = '+ _tabIndex.toString()  +  toobarClassNameList[_tabIndex].toString());
              // print('当前G.tabIndex = '+ G.tabIndex.toString()  +  '    i == $i');
            },
          ),
        );
        list.add(item);
      } else {
        Container item = Container(
          // padding: (i==1)? _padding2 : (i==3)? _padding3: _padding,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              constraints: BoxConstraints(minWidth: getScreenWidth() / 5),
              color: Colors.red,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[],
              ),
            ),
            onTap: () {},
          ),
        );
        list.add(item);
      }
    }
    return list;
  }

  _getNavIcon(int curIndex) {
    if (curIndex == 2) {
      return Icon(
        tabIcons[curIndex],
        color: Theme.of(context).accentColor,
        size: 50,
      );
    }
    if (curIndex == _tabIndex) {
      //color
      return Icon(
        tabIcons[curIndex],
        color: Theme.of(context).accentColor,
        size: 20,
      );
    } else {
      return Icon(
        tabIcons[curIndex],
        size: 20,
        color: Theme.of(context).primaryTextTheme.caption.color,
      );
    }
  }

  _getNavTitle(int curIndex) {
    if (curIndex == _tabIndex) {
      return Text(
        appBarTitles[curIndex],
        style: TextStyle(fontSize: 10, color: Theme.of(context).accentColor),
      );
    } else {
      return Text(
        appBarTitles[curIndex],
        style: TextStyle(
            fontSize: 10,
            color: Theme.of(context).primaryTextTheme.caption.color),
      );
    }
  }

  String _platform = "";
  PackageInfo packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    version: 'Unknown',
    buildNumber: 'Unknown',
  );

  @override
  void initState() {
    //弹窗菜单
    controller =
        AnimationController(duration: Duration(milliseconds: 500), vsync: this);
    animation =
        CurvedAnimation(parent: controller, curve: Curves.easeInOutBack);
    animation.addListener(() {
      setState(() {
        _currentValue = controller.value.toString();
      });
    });

    fullSavePath = "";
    String fileName;
    pr = ProgressDialog(
      context,
      type: ProgressDialogType.Download,
      textDirection: TextDirection.ltr,
      isDismissible: false,
    );

    pr.style(
      message: '下载中，请等待...',
      borderRadius: 10.0,
      backgroundColor: Colors.white,
      elevation: 10.0,
      insetAnimCurve: Curves.easeInOut,
      progress: 0.0,
      progressWidgetAlignment: Alignment.center,
      maxProgress: 100.0,
      progressTextStyle: TextStyle(
          color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.w400),
      messageTextStyle: TextStyle(
          color: Colors.black, fontSize: 18.0, fontWeight: FontWeight.w600),
    );

    FlutterDownloader.registerCallback(downloading);

    if (Platform.isAndroid) {
      _platform = "Android";
    }
    if (Platform.isIOS) {
      _platform = "IOS";
    }

    //获取比对版本信息
    G.req.vertion.getVertionInfo(platformName: _platform).then((rs) {
      if (rs.data != null) {
        //获取接口版本
        int vertion = rs.data['version'] as int; //比对数值
        String vertionCode = rs.data['versionCode'];
        String summary = rs.data['Summary'];
        String downloadUrl = rs.data['downloadUrl'];
        fileName = downloadUrl.substring(
            downloadUrl.lastIndexOf('/') + 1, downloadUrl.length);

        //获取APP信息
        _initPackageInfo().then((value) {
          // appName:null  packageInfo.appName;
          // buildNumber:"1"
          // packageName:"com.xushuhao.ckxttapp"  packageInfo.packageName;
          // version:"1.0.0"

          //版本名
          String version = packageInfo.version;
          G.user.data.appVerstion = version;
          //版本号
          int buildNumber = int.parse(packageInfo.buildNumber);
          //比对
          if (buildNumber < vertion && summary.toString().trim() != "") {
            RouteTransition(XDialogPage(
              "已检测到最新的版本信息。为保证最佳的使用体验，建议进行升级操作！\n\n\n新版本内容主要包括：\n\n" + summary,
              title: "版本升级",
              buttonName: "马上升级",
              callBack: () async {
                Navigator.of(context).pop();
                if (Platform.isIOS) {
                  await G.openToAppStore(downloadUrl);
                  return;
                } else {
                  await pr.show();
                  if (await G.checkPermission(context)) {
                    fullSavePath = await G.createFileDir('APK');
                    // 设置下载回调
                    ReceivePort _port = ReceivePort();
                    IsolateNameServer.registerPortWithName(
                        _port.sendPort, 'downloader_send_port');
                    _port.listen((dynamic data) async {
                      String id = data[0];
                      DownloadTaskStatus status = data[1];
                      int progress = data[2];

                      if (status.value == 2) {
                        pr.update(
                            progress: progress.toDouble(), message: "下载中，请稍后…");
                      }

                      if (status.value == 4) {
                        print("下载异常，请稍后重试");
                        G.showWrongToast('下载异常，请稍后重试!');
                        if (pr.isShowing()) {
                          pr.hide();
                        }
                      }

                      if (status.value == 3) {
                        if (pr.isShowing()) {
                          pr.hide();
                          InstallPlugin.installApk(
                                  fullSavePath + "/" + fileName, G.appID)
                              .then((result) {
                            print('install apk $result');
                          }).catchError((error) {
                            print('install apk error: $error');
                          });
                        }
                      }
                    });

                    await FlutterDownloader.enqueue(
                      url: downloadUrl,
                      savedDir: fullSavePath,
                      showNotification: true,
                      // show download progress in status bar (for Android)
                      openFileFromNotification:
                          true, // click on notification to open downloaded file (for Android)
                    );
                  }
                }
              },
            )).pushTransRoute(context);
          }
        });
      }
    });
    super.initState();
  }

  static downloading(String id, DownloadTaskStatus status, int progress) {
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port');
    send.send([id, status, progress]);
  }

  Future<void> _initPackageInfo() async {
    final PackageInfo info = await PackageInfo.fromPlatform();
    setState(() {
      packageInfo = info;
    });
  }
}
